﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using simpleHotel.Client.UserControls;
using DevExpress.Utils.Drawing;
using DevExpress.XtraBars.Ribbon;
using simple.Utilities;
using System.IO;
using simpleHotel.Client.HotelReference;
using DevExpress.XtraEditors.Controls;
using System.Drawing.Imaging;
using simpleHotel.Business;
using System.Text.RegularExpressions;


namespace simpleHotel.Client.Hotel
{
    
    public partial class ucHotelDetail : BaseUserControl
    {
        private int _hotelId = -1;
        public int HotelId {
            get { return this._hotelId; }
            set { this._hotelId = value; }
        }

        private HotelService _service;
        public HotelService Service
        {
            get { return this._service; }
            private set { this._service = value; }
        }

        private bool _isNewMode = true;
        public bool IsNewMode 
        {
            get { return this._isNewMode; }
            set { 
                this._isNewMode = value;
                InitMode();
            }
        }

        private void InitMode() 
        { 
                
        }

        public ucHotelDetail()
        {
            InitializeComponent();
            InitGalleryControl();

            //init service
            this._service = new HotelService();
        }

        private void InitGalleryControl() {
            //Image im1 = Image.FromFile("c:\\Images\\BMW.jpg");
            //Image im2 = Image.FromFile("c:\\Images\\Ford.jpg");
            //Image im3 = Image.FromFile("c:\\Images\\MercedecBenz.jpg");
            //Image im4 = Image.FromFile("c:\\Images\\AnneDodsworth.jpg");
            //Image im5 = Image.FromFile("c:\\Images\\HannaMoos.jpg");
            //Image im6 = Image.FromFile("c:\\Images\\JanetLeverling.jpg");

            this.galleryControl1.Gallery.ItemImageLayout = ImageLayoutMode.ZoomInside;
            this.galleryControl1.Gallery.ImageSize = new Size(120, 90);
            this.galleryControl1.Gallery.ShowItemText = true;

            GalleryItemGroup group1 = new GalleryItemGroup();
            group1.Caption = "Ảnh nhỏ";
            this.galleryControl1.Gallery.Groups.Add(group1);

            //GalleryItemGroup group2 = new GalleryItemGroup();
            //group2.Caption = "People";
            //this.galleryControl1.Gallery.Groups.Add(group2);

            //group1.Items.Add(new GalleryItem(im1, "BMW", ""));
            //group1.Items.Add(new GalleryItem(im2, "Ford", ""));
            //group1.Items.Add(new GalleryItem(im3, "Mercedec-Benz", ""));

            //group2.Items.Add(new GalleryItem(im4, "Anne Dodsworth", ""));
            //group2.Items.Add(new GalleryItem(im5, "Hanna Moos", ""));
            //group2.Items.Add(new GalleryItem(im6, "Janet Leverling", ""));
        }

        private void label3_Click(object sender, EventArgs e)
        {

        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            
        }

        private void pictureBox1_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Multiselect = false;
            ofd.Filter = ".jpg files|*.jpg|.png files|*.png";
            if (ofd.ShowDialog() == DialogResult.OK) {
                this.pictureBox1.ImageLocation = ofd.FileName;
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //add files to small images
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Filter = ".jpg files|*.jpg|.png files|*.png";
            ofd.Multiselect = true;
            string notAllowedFiles = string.Empty;
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                if (ofd.FileNames != null)
                {
                    foreach (var fn in ofd.FileNames) {
                        if (!ImageHelper.IsSizeAllowed(fn))
                        {
                            notAllowedFiles += Path.GetFileName(fn) + ", ";
                            continue;
                        }
                        var img = Image.FromFile(fn);
                        this.galleryControl1.Gallery.Groups[0].Items.Add(new GalleryItem(img, "", ""));
                    }

                    if (notAllowedFiles != string.Empty) {
                        MessageBox.Show("File lỗi: \r\n" + notAllowedFiles.Trim(' ',','), "Kích thướt file phải nhỏ hơn 800KB");
                    }
                }
                
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            DeleteSmallImage();
        }

        private void DeleteSmallImage() {
            foreach (GalleryItem item in this.galleryControl1.Gallery.Groups[0].Items)
            {
                if (item.Checked)
                {
                    this.galleryControl1.Gallery.Groups[0].Items.Remove(item);
                    return;
                }
            }
        }
        //Nghiep Added
        private void GetHotelService(int hotelID)
        {
            var dt = this.Service.GetServiceByHotelID(hotelID);
           
        }
        private void GetProvinces()
        {
            var dt = this.Service.LoadProvince();
            this.ddlProvince.Properties.Items.Clear();
            foreach (DataRow row in dt.Rows) 
            {
                this.ddlProvince.Properties.Items.Add(row["Description"].ToString());
            }
        }

        private void GetStandards() 
        {
            var dt = this.Service.LoadStandards();
            this.ddlStandard.Properties.Items.Clear();
            foreach (DataRow row in dt.Rows)
            {
                this.ddlStandard.Properties.Items.Add(row["Description"].ToString());
            }
        }

        private void GetRoomTypes()
        {
            this.listRoomType.Items.Clear();
        }

        private void ucHotelDetail_Load(object sender, EventArgs e)
        {
            if (this.HotelId == -1) // add new mode
            {
                GetProvinces();
                GetRoomTypes();
                GetStandards();
                BlankControls();
            }
            else
            {
                GetProvinces();
                loadRoomType();
                var table = this.Service.GetHotel(this.HotelId);
                if (table != null)
                {
                    var row = table.Rows[0];
                    this.ddlProvince.SelectedIndex = int.Parse(row["ProvinceID"].ToString());
                    this.txtName.Text = row["HotelName"].ToString();
                    this.txtAdd1.Text = row["Address1"].ToString();
                    this.txtAdd2.Text = row["Address2"].ToString();
                    this.txtAdd3.Text = row["Address3"].ToString();
                    this.txtDescription.Text = row["Description"].ToString();
                    this.txtEmail.Text = row["Email"].ToString();
                    this.txtFax.Text = row["Fax"].ToString();
                    this.txtPhone1.Text = row["Phone1"].ToString();
                    this.txtPhone2.Text = row["Phone2"].ToString();
                    this.txtRoomCount.Text = row["TotalRoom"].ToString();
                    //this.txtWeb.Text
                    pictureBox1.ImageLocation = row["images"].ToString();
                }
            }
        }

        private void BlankControls() {
            this.txtName.Text = string.Empty;

        }

        private void listBoxControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                this.txtRoomType.Text = this.listRoomType.SelectedItem.ToString();
            }
            catch
            { 
            }
        }

        private void button4_Click(object sender, EventArgs e)
        {
            AddRoomType();
        }

        private void loadRoomType()
        {
            var dt = this.Service.GetCateRoomHotelID(HotelId);
            foreach (DataRow row in dt.Rows)
            {
                this.listRoomType.Items.Add(row["Name"].ToString());
            }
        }
        private void AddRoomType()
        {
            var roomType = this.txtRoomType.Text.Trim();
            if (roomType == string.Empty)
            {
                MessageBox.Show("Xin nhập loại phòng");
                return;
            }

            if (!ExistsRoomType(roomType))
            {
                _service = new HotelService();
                
                this.listRoomType.Items.Add(roomType);
            }
            else
                MessageBox.Show("Loại phòng '" + roomType + "' đã tồn tại.", "Thông báo");
        }

        private bool ExistsRoomType(string roomType)
        {
            foreach (string item in this.listRoomType.Items)
            {
                if (item == roomType.Trim())
                    return true;
            }
            return false;
        }

        private void DeleteRoomType() 
        {
            var item = this.listRoomType.SelectedItem;
            if (item != null)
                this.listRoomType.Items.Remove(item);
        }

        private void button5_Click(object sender, EventArgs e)
        {
            DeleteRoomType();
        }

        private void button3_Click(object sender, EventArgs e)
        {
            DeleteAllSmallImages();
        }

        private void DeleteAllSmallImages() {
            //delete all small images
            var dr = MessageBox.Show("Bạn có muốn xóa hết ảnh trong danh sách ?", "Thông báo", MessageBoxButtons.YesNo);
            if (dr == DialogResult.Yes)
            {
                this.galleryControl1.Gallery.Groups[0].Items.Clear();
            }
        }

        private void Save() 
        {
            var isValid = ValidateControls();
            if (!isValid) {
                MessageBox.Show("Chưa Nhập Tên Khách Sạn");
                //do set focus, ....
                txtName.Focus();
                return;
            }

            if (!CheckEmail(txtEmail.Text))
            {
                MessageBox.Show("Email không đúng định dạng!");
                txtEmail.Focus();
                return;
            }
            var hotelInfo = new HotelInfoDTO { 
                Address1 = txtAdd1.Text.Trim(),
                Address2 = txtAdd2.Text.Trim(),
                Address3 = txtAdd3.Text.Trim(),
                CreatedDate = DateTime.Now,
                Description = txtDescription.Text.Trim(),
                Email = txtEmail.Text.Trim(),
                Phone1 = txtPhone1.Text.Trim(),
                phone2 = txtPhone2.Text.Trim(),
                Term = string.Empty,
                HotelName = txtName.Text.Trim(),
                TotalRoom = int.Parse(txtRoomCount.Text.Trim()),
                Price = 10m,
                image = GetImage(),
                SmallImages = GetSmallImages(),
            };

            this.Service.CreateHotel(hotelInfo);
            MessageBox.Show("Success");
        }

        private string GetImage() 
        {
            return ImageHelper.ImageToBase64(this.pictureBox1.Image, ImageFormat.Jpeg);
        }

        private string[] GetSmallImages() 
        {
            var list = new List<string>();
            for (int i = 0; i < this.galleryControl1.Gallery.Groups[0].Items.Count; i++) {
                var item = this.galleryControl1.Gallery.Groups[0].Items[i];
                list.Add(ImageHelper.ImageToBase64(item.Image, ImageFormat.Jpeg));
            }
            return list.ToArray();
        }

        private bool ValidateControls()
        {
            if (txtName.Text == "")
            {
                return false;
            }
            return true;
        }

        private bool CheckEmail(string EmailAddress)
        {
            string strPattern = "^([0-9a-zA-Z]([-.\\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\\w]*[0-9a-zA-Z]\\.)+[a-zA-Z]{2,9})$";
            if (System.Text.RegularExpressions.Regex.IsMatch(EmailAddress, strPattern))
            { return true; }
            return false;
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (HotelId != -1)
            {
                update();
            }
            else
            {
                Save();
            }
        }

        private void update()
        {
            var hotelInfo = new HotelInfoDTO
            {
                ID = HotelId, //1
                Price = 250000,//2
                HotelName = txtName.Text.Trim(),//3
                ProvinceID = 1,//4
                RangeID = 1, //5
                ServiceID = 1,//6
                TotalRoom = int.Parse(txtRoomCount.Text.Trim()),//7
                image = GetImage(),//8
                Description = txtDescription.Text.Trim(),//9
                Address1 = txtAdd1.Text.Trim(),//10
                Email = txtEmail.Text.Trim(),//11
                Phone1 = txtPhone1.Text.Trim(),//12
                Fax = txtPhone1.Text.Trim(),//13
                phone2 = txtPhone2.Text.Trim(),//14
                Address2 = txtAdd2.Text.Trim(),//15
                Address3 = txtAdd3.Text.Trim(),//15
                CreatedDate = DateTime.Now,//7Term = string.Empty,   //12 
                SmallImages = GetSmallImages(),//15
            };
            Service.UpdateHotel(hotelInfo);          
            Service.updateHotelImage(hotelInfo);
            MessageBox.Show("Update thanh cong");
        }
    }
}
